package com.firebird.app.kotlin.stock.trend.net

import com.android.volley.NetworkResponse
import com.android.volley.ParseError
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.HttpHeaderParser
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.io.UnsupportedEncodingException
import java.lang.reflect.Type
import java.nio.charset.Charset


/**
 * 自定义Volley的Request对象，用于将请求来的Json数据直接转化为对象
 * @author ljk
 * @date   2019年11月7日
 */
class ObjectRequest<T>(method: Int, type: Type, url: String?, private val successListener: Response.Listener<T>, errorListener: Response.ErrorListener?) : Request<T>(method, url, errorListener) {
    private var gson: Gson?=null
    private var mGsonType: Type?=null
    override fun deliverResponse(response: T) {
        successListener.onResponse(response)
    }

    override fun parseNetworkResponse(response: NetworkResponse): Response<T> {
        return try {
            var result: T? = null
           val charset: Charset = Charsets.UTF_8
           // json = String(buffer, charset)
           // val jsonStr = String(response.data, HttpHeaderParser.parseCharset(response.headers))
            val jsonStr= String(response.data,charset)
            result = gson!!.fromJson(jsonStr, mGsonType)
            Response.success(result, HttpHeaderParser.parseCacheHeaders(response))
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
            Response.error(ParseError(e))
        }
    }

    init {
        gson = GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
        //this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();// 不转换没有 @Expose 注解的字段
        mGsonType = type
    }
}

